package com.raos.example.thread.service;

import com.raos.example.thread.entity.UserEntity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 异步操作调用实现类 -- 含数据返会进行同步操作  -- 试行
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2022/6/16 11:30
 */
@Component
@Slf4j
public class OtherService {

    @Async
    @SneakyThrows
    public void addPoints(UserEntity userEntity, final CountDownLatch countDownLatch, Map<String, Object> data) {
        try {
            log.info("当前添加积分用户=" + userEntity);
            Thread.sleep(200); //模拟添加积分耗时
            data.put("points", 100);
        } catch (InterruptedException e) {
            e.printStackTrace();
            data.put("points", 0);
        }
        countDownLatch.countDown();
    }

    @Async("otherPoolTaskExecutor")
    @SneakyThrows
    public void sendSms(UserEntity userEntity, final CountDownLatch countDownLatch, Map<String, Object> data) {
        try {
            log.info("当前发送短信给用户=" + userEntity);
            Thread.sleep(200); //模拟发送短信耗时
            data.put("isSend", true);
        } catch (InterruptedException e) {
            e.printStackTrace();
            data.put("isSend", false);
        }
        countDownLatch.countDown();
    }

}
